from rest_framework.generics import GenericAPIView, ListAPIView, ListCreateAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status

from meiduo_admin.serializers.users import AdminAuthSerializer, UserSerializer
from users.models import User


# POST /meiduo_admin/authorizations/
#管理员登录
class AdminAuthorizeView(APIView):
    def post(self, request):
        """
        管理员登录:
        1. 获取参数并进行校验
        2. 服务器签发jwt token数据
        3. 返回应答
        """
        # 1. 获取参数并进行校验
        serializer = AdminAuthSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 2. 服务器签发jwt token数据(create)
        serializer.save()

        # 3. 返回应答
        return Response(serializer.data, status=status.HTTP_201_CREATED)

#查询普通用户数据
class UserInfoView(ListCreateAPIView):
    permission_classes = [IsAdminUser]
    #指定用户所使用的序列化器类
    serializer_class = UserSerializer

    def get_queryset(self):
        "返回视图所需要的查询集合"
        # 1.获取keyword关键字
        keyword = self.request.query_params.get('keyword')

        # 2.查询普通用户数据
        if keyword is None or keyword == '':
            users = User.objects.filter(is_staff=False)
        else:
            users = User.objects.filter(is_staff=False, username__contains=keyword)

        return users

    # def get(self,request):
    #
    #     """获取普通用户组
    #     1.获取keyword关键字
    #     2.查询普通用户数据
    #     3.将用户数据序列化返回
    #     """
    #
    #     #查询普通用户数据
    #     users = self.get_queryset()
    #     # 3.将用户数据序列化返回
    #     serializer = UserSerializer(users,many = True)
    #     return Response(serializer.data)

    #
    #
    # #新增用户
    #
    # #POST /meiduo_admin/users
    # def post(self,request):
    #     """
    #     新增用户数量
    #     1.获取参数并校验
    #     2.创建并保存新用户数据
    #     3.将新用户数据序列化返回
    #     """
    #     # 1.获取参数并校验
    #     serializer = self.get_serializer(data = request.data)
    #     serializer.is_valid(raise_exception = True)
    #     # 2.创建并保存新用户数据
    #     serializer.save()   #create
    #     # 3.将新用户数据序列化返回
    #     return Response(serializer.data,status=status.HTTP_201_CREATED)
    #

















